<?php

class ws{

    private $server;

    public function __construct($host,$port,$document_root=null){
        $this->server=new swoole_websocket_server($host,$port);
        if($document_root){
            $this->server->set([
                'enable_static_handler'=>true,
                'document_root'=>$document_root
            ]);
        }
        $this->server->set([
            'worker_num'=>2,
            'task_worker_num'=>2
        ]);
        $this->server->on('open',[$this,'onOpen']);
        $this->server->on('message',[$this,'onMessage']);
        $this->server->on('task',[$this,'onTask']);
        $this->server->on('finish',[$this,'onFinish']);
        $this->server->on('close',[$this,'onClose']);
        $this->server->start();
    }
    public function onOpen($server,$request){
        echo "handshake: {$request->fd}".PHP_EOL;
        if($request->fd ==1){
            swoole_timer_tick(2000,function($timer_id){
                echo "2s:timerId:{$timer_id}".PHP_EOL;
            });
        }
    }
    public function onMessage($server,$frame){
        echo "receive from {$frame->fd}:{$frame->data}".PHP_EOL;
        $data=[
            'task'=>1,
            'fd'=>$frame->fd
        ];
        $server->task($data);
        swoole_timer_after(5000,function() use($server,$frame){
            echo "5 after:";
            $server->push($frame->fd,"server-5s-after");
        });
        $server->push($frame->fd,date("Y-m-d H:i:s")."-->".$frame->data);
    }
    public function onTask($server,$taskId,$workerId,$data){
        print_r($data);
        sleep(10);
        return "on task finish";

    }
    public function onFinish($server,$taskId,$data){
        echo "taskId:{$taskId}".PHP_EOL;
        echo "finish data:{$data}".PHP_EOL;


    }
    public function onClose($server,$fd){
        echo "client:{$fd} close".PHP_EOL;
    }

}

























